package vcp.server.deamontasks;

import java.io.IOException;
import java.util.List;
import java.util.TimerTask;

import ocsf.server.ConnectionToClient;

import org.joda.time.DateTime;

import vcp.client.request.response.ResponseRefresh;
import vcp.entity.Complaint;
import vcp.enums.ComplaintType.ComplaintStatus;
import vcp.server.DAO.ComplaintDAO;
import vcp.server.interfaces.IServer;
import vcp.server.utility.SystemClock;

/**
 * 
 * @author VCP team
 *         <p>
 *         class handles opened complaint and makes sure that customer gets
 *         answer within 24 hours
 *         </p>
 */
public class User24HourComplaintNotificationTask extends TimerTask
{
	private final IServer server;

	/**
	 * class constructor
	 * 
	 * @param serverDeamon
	 */
	public User24HourComplaintNotificationTask ( IServer serverDeamon )
	{
		this.server = serverDeamon;
	}

	@Override
	public void run ()
	{
		synchronized (this.server.getDBLock())
		{
			System.out.println("User24HourComplaintNotificationTask:  TrueTime:" + new DateTime() + "  SysTime:" + SystemClock.getClockInstance().getSystemDateTime());
			ComplaintDAO complaintDAO = new ComplaintDAO();
			List <Complaint> allOpenComplaint = complaintDAO.findAllOpenComplaints();

			for ( Complaint complaint : allOpenComplaint )
			{
				int hourOfPeriod = SystemClock.getClockInstance().hoursBetweenCurrentHour(complaint.getOpenDate());
				if ( hourOfPeriod >= 24 )
				{
					complaint.setStatus(ComplaintStatus.PENDING);
					complaintDAO.updateComplaintStatus(complaint.getID(), complaint.getStatus());

					for ( ConnectionToClient client : this.server.getConnections() )
					{
						try
						{
							client.sendToClient(new ResponseRefresh(complaint));
						}
						catch ( IOException e )
						{
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
}
